import dayjs from 'dayjs'

/**
 * 节流原理：在一定时间内，只能触发一次
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
let timer, flag: boolean
export function throttle(func: Function, wait = 500, immediate = true) {
  if (immediate) {
    if (!flag) {
      flag = true
      // 如果是立即执行，则在wait毫秒内开始时执行
      typeof func === 'function' && func()
      timer = setTimeout(() => {
        flag = false
      }, wait)
    }
  } else {
    if (!flag) {
      flag = true
      // 如果是非立即执行，则在wait毫秒内的结束处执行
      timer = setTimeout(() => {
        flag = false
        typeof func === 'function' && func()
      }, wait)
    }
  }
}

/**
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
let timeout: any = null
export function debounce(func: Function, wait = 500, immediate = false) {
  // 清除定时器
  if (timeout !== null) clearTimeout(timeout)
  // 立即执行，此类情况一般用不到
  if (immediate) {
    var callNow = !timeout
    timeout = setTimeout(function () {
      timeout = null
    }, wait)
    if (callNow) typeof func === 'function' && func()
  } else {
    // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
    timeout = setTimeout(function () {
      typeof func === 'function' && func()
    }, wait)
  }
}

// 显示本地图片
export function pic(name: string) {
  return import.meta.env.VITE_LOCAL_PIC + name
}

/**
 *
 * @param time 判断传入的时间是否过期
 * @param debuff 提前量(比如提前一分钟过期)
 * @returns
 */
export function isExpired(time: string | number, debuff: number): boolean {
  const currentTime = new Date().getTime() / 1000
  const toCompare = parseInt(time + '')

  return currentTime + debuff > toCompare
}

export function dataFormatYYmmdd(timeStr: string) {
  const date = new Date(timeStr.replace(/-/g, '/'))
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  return `${year}.${month}.${day}`
}

/**
 *
 * @param {*} number
 * @param {*} step
 * @param {*} type 0:四舍五入;1:向下取整;向上
 */
export function numBits(number: any, step = 2, type = 0) {
  let f = parseFloat(number)
  if (isNaN(f)) {
    // //console.log('number格式错误')
    return 0.0
  }
  if (type == 0) {
    f = Math.round(number * Math.pow(10, step)) / Math.pow(10, step)
  }
  if (type == 1) {
    f = Math.floor(number * Math.pow(10, step)) / Math.pow(10, step)
  }
  let s = f.toString()
  let rs = s.indexOf('.')
  if (rs < 0) {
    rs = s.length
    s += '.'
  }
  while (s.length <= rs + step) {
    s += '0'
  }
  return s
}

/**
 * 根据传入时间返回 剩余天数 小时数(0-23) 分钟数(0-59)
 */
export function getRemainTime(endTime: string) {
  var remainTime = Date.parse(endTime) - Date.parse(new Date().toISOString())
  var seconds = Math.floor((remainTime / 1000) % 60)
  var minutes = Math.floor((remainTime / 1000 / 60) % 60)
  var hours = Math.floor((remainTime / (1000 * 60 * 60)) % 24)
  var days = Math.floor(remainTime / (1000 * 60 * 60 * 24))

  return {
    total: remainTime,
    days: days,
    hours: hours,
    minutes: minutes,
    seconds: seconds
  }
}

export function generateUniqueId() {
  // 获取当前时间戳
  const timestamp = new Date().getTime()

  // 生成随机数作为额外的随机性
  const random = Math.floor(Math.random() * 10000)

  // 拼接时间戳和随机数
  const uniqueId = timestamp.toString() + random.toString()

  return uniqueId
}

export function showSugar(v: number) {
  // const { t } = useI18n()
  // switch (v) {
  //   case 0:
  //     return t('shop.product.sugarData.z')
  //   case 30:
  //     return t('shop.product.sugarData.a')
  //   case 50:
  //     return t('shop.product.sugarData.b')
  //   case 70:
  //     return t('shop.product.sugarData.c')
  //   case 100:
  //     return t('shop.product.sugarData.d')
  //   case 120:
  //     return t('shop.product.sugarData.e')
  // }
  return v + '%'
}
export function showCold(v: number) {
  const { t } = useI18n()
  switch (v) {
    case 20:
      return t('shop.product.coldData.a')
    case 10:
      return t('shop.product.coldData.b')
    case 30:
      return t('shop.product.coldData.c')
  }
}

export function orderType(num: number) {
  const { t } = useI18n()
  switch (num) {
    case 20:
      return t('take.order.charge')
    case 30:
      return t('take.order.mem')
  }
}

export function orderStatusWithTime(status: number, time: string) {
  if (status == 0) return 0
  if (status == 1) {
    const today = dayjs().format('YYYY-MM-DD')
    const orderDate = dayjs(time).format('YYYY-MM-DD')

    if (today == orderDate) {
      return 1
    }
    return 2
  } else {
    return 2
  }
}

export function showAgentType(v: number) {
  const { t } = useI18n()
  switch (v) {
    case 0:
      return t('agent.status0')
    case 10:
      return t('agent.status10')
    case 15:
      return t('agent.status15')
    case 20:
      return t('agent.status20')
    case 30:
      return t('agent.status30')
    case 40:
      return t('agent.status40')
    case 100:
      return t('agent.status100')
  }
}

export function orderStatus(num: number) {
  const { t } = useI18n()
  switch (num) {
    case 0:
      return t('take.order.status0')
    case 1:
      return t('take.order.status1')
    case 2:
      return t('take.order.status2')
  }
}

export function showName(obj: ApiOrderProductInfo) {
  return localStorage.getItem('localeLang') == 'zhCn' ? obj.productNameZh : obj.productNameRu
}
